<template>
  <div v-if="loginVisible"
    class="tw-loginpage" :class="{xbg2: bgtimer, inDialog: props.inDialog}">
    <h1 class="tw-loginpage-header" v-if="!props.inDialog">
      <a v-if="!logoloading"></a>
      <a v-else>
        <template v-if="$store.state
          && $store.state.custLogoInfo
          && $store.state.custLogoInfo.logoUrl">
          <img :src="$store.state.custLogoInfo.logoUrl" />
        </template>
        <img src="@assets/images/Logo.png" alt="">
      </a>
    </h1>
    <main class="tw-loginpage-body">
      <div class="tw-login">
        <div class="text-center mb-medium" style="display: flex;justify-content: center;">
          <div class="tw-login-tabpanel">
            <!-- <div class="tw-login-tabitem" @click="changeLoginType()"
              :class="{ 'active': !isUsernameLogin }" v-if="!props.inDialog">
              扫码登录
            </div> -->
            <div class="tw-login-tabitem" @click="changeLoginType()"
              :class="{ 'active': isUsernameLogin }">
              账户登录
            </div>
          </div>
        </div>

        <!-- 帐号密码登录 -->
        <div class="tw-login-panel" v-if="isUsernameLogin">
          <div class="mb-tiny" style="display: flex;justify-content: space-between;align-items: center;">
            &nbsp;
          </div>
          <div class="tw-login-inputbox mb-medium">
            <i class="tw-loginicon x48 xuser"></i>
            <input v-model="formData.username" type="text" placeholder="用户名" @keydown.enter="handleLogin()" />
          </div>

          <div class="tw-login-inputbox mb-medium">
            <i class="tw-loginicon x48 xpwd"></i>
            <input v-model="formData.password" type="password" placeholder="请输入密码" @keydown.enter="handleLogin()" />
          </div>

          <div class="tw-login-inputbox xvalidation mb-medium" v-if="captchaVisibale">
            <i class="tw-loginicon x48 xpwd"></i>
            <input v-model="formData.captchaText" type="text" placeholder="请输入验证码" @keydown.enter="handleLogin()" />

            <img v-if="verifyCodeType === 'eco' &&
              captchaData.base64Img
              " :src="captchaData.base64Img" alt="验证码" title="点刷新验证码"
              @click="$api.captchaView()" />

            <div v-if="verifyCodeType === 'local'" id="vcode" class="tw-login-verifycodebox"></div>
          </div>

          <div class="tw-login-inputbox mb-medium" v-if="userOrgList.length > 0">
            <i class="tw-loginicon x48 xuser"></i>
            <el-select v-model="formData.uid" placeholder="请选择机构">
              <el-option v-for="user in userOrgList" :key="user.userId" :label="user.orgName"
                :value="user.userId"></el-option>
            </el-select>
          </div>

          <div class="mb-tiny">
            <a class="tw-loginbtn" @click="handleLogin">登 录</a>
          </div>
        </div>

        <!-- 扫码登录 -->
        <div class="tw-login-panel tw-login-qrcode" v-else>
          <div class="mb-tiny" style="display: flex;justify-content: space-between;align-items: center;">
            &nbsp;
          </div>
          <div style="display: flex;justify-content: center;align-items: flex-end;" v-if="qrCode">
            <div class="tw-login-qrcodebox">
              <img :src="qrCode" />
              <div class="tw-qrcode-refresh" v-if="invalidCode">
                <p>二维码已失效</p>
                <a class="tw-btn xweaking" @click="getTeachQRCode">刷新</a>
              </div>

              <div>
                <a @click="getTeachQRCode">刷新二维码</a>
              </div>
            </div>
            <div class="tw-loginicon xscan ml-tiny"></div>
          </div>

          <div class="mb-large pb-large">
            <div class="mt-medium" style="font-size: 16px;">
              请使用{{ qrcodeType === 1 ? "校比邻" : "天闻AI课堂" }}扫码登录
            </div>
          </div>
        </div>

        <!-- 第三方登录 -->
        <!-- <div v-if="isUsernameLogin">
          <div class="tw-login-download">
            其他客户端：
            <div class="tw-loginicon xandroid ml-tiny" @click="openQrModal('android')">&nbsp;</div>
            <div class="tw-loginicon xwindows ml-tiny" @click="downloadApp">&nbsp;</div>
          </div>
        </div>
        <div v-else>
          <el-divider>其他登录方法</el-divider>
          <div class="tw-login-weixin">
            <div class="weixin" @click="LoginThirdPart('1')">
              <img src="./images/wx.png" alt="">
              <div>微信登陆</div>
            </div>
          </div>
        </div> -->
      </div>
    </main>

    <el-dialog class="xappqrcode" v-model="qrCodeModal.visible" width="500">
      <template #header>下载App</template>

      <div class="tw-appqrcode text-center pb-large">
        <div v-if="qrCodeModal.type === 'android'">
          <QRCode class="pt-small" :url="appQrCode.android" />
          <br />
          <a class="tw-btn xweaking mt-small" href="./files/Aiclass.apk">下载APK</a>
        </div>

        <div v-if="qrCodeModal.type === 'ios'">
          <QRCode class="pt-small" :url="appQrCode.ios" />
          <br />
          <a class="tw-btn xweaking mt-small"
            href="https://apps.apple.com/cn/app/%E5%A4%A9%E9%97%BBai%E8%AF%BE%E5%A0%82/id1544013121"
            target="_blank">IOS应用商店</a>
        </div>
      </div>
    </el-dialog>

    <div class="tw-loginpage-copyright" style="color: #646C9C;" v-if="!props.inDialog">
      Copyright © 2008-现在 天闻数媒科技（北京）有限公司, All Rights Reserved
      {{ $app.appVersion }}
    </div>

    <!-- <secondaryValidation v-if="secondaryValidationVisible" :visible.sync="secondaryValidationVisible" @succeed="confirmSecondaryValidation"></secondaryValidation> -->
  </div>
</template>
<script>
export default {
  name: 'page-login'
}
</script>
<script setup>
  import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
  // import { useStore } from 'vuex'
  import { useRouter, useRoute } from 'vue-router'

  import * as cnt from '@/management/utils/constant.ts'
  import * as $api from '@/management/api/eco/auth'
  import QRCode from '@/management/components/QRCode.vue'
  import { downLoadApp } from '@/management/api/eco/appcenter'

  // import secondaryValidation from '@/public/views/login/secondary-validation'
import store from '@/management/store/index'
  // const store = useStore()
  const route = useRoute()
  const router = useRouter()
  const props = defineProps({
    'inDialog': {
      type: Boolean,
      default: false
    }
  })
  const emit = defineEmits(['close'])
  const logoloading = ref(true)
  const captchaVisibale = ref(false)
  const isUsernameLogin = ref(true)
  const loginVisible = ref(false)
  const userOrgList = reactive([])
  const formData = reactive({
    username: '',
    password: '',
    uid: '',
    captchaCode: '',
    captchaText: ''
  })
  const errorMsg = ref('')
  const sending = ref(false)
  const qrCode = ref('')
  const screenId = ref('')
  const loopTimer = reactive({value: null})
  const captchaData = reactive({
    base64Img: '',
    captchaCode: ''
  })
  const times = ref(0)
  const userLocalKey = `${window.$app.appId}_local_user`

  const appQrCode = reactive({
    size: $app.widthRate * 320,
    ios: 'https://apps.apple.com/cn/app/%E5%A4%A9%E9%97%BBai%E8%AF%BE%E5%A0%82/id1544013121',
    android: window.origin + '/files/Aiclass.apk'
  })
  const qrCodeModal = reactive({
    type: '',
    visible: false
  })

  const qrcodeType = ref(1)
  const verifyCodeType = ref('local')  // local-前端本地 eco-ECO验证
  const verifyCode = reactive({value: null})
  const invalidCodeTime = reactive({value: null})
  const loginThirdParams = reactive({})
  const invalidCode = ref(false)
  const secondaryValidationVisible = ref(false)
  const doubleAuthentic = ref(false)
  const bgtimer = ref(false)
  const bgtimers = reactive({value: null})
  const logoInfo = reactive({
    logoid: '',
    appid: '',
    logotype: '',
    logoUrl: '',
    title: '',
    copyright: '',
    versionNumber: '',
    businessLicense: '',
    recordNumber: '',
    recordConnection: '',
    iconUrl: '',
    domainUrl: '',
    platformTitle: '',
    loginTitle: '',
    createTime: '',
    lastmodifytime: '',
    status: ''
  })

  const grantType = ref('password')
  const accessToken = ref('')

  const handleUserInfo = async (user) => {
    sending.value = false

    // 只有状态为正常的用户才允许登录系统
    // 1:正常 2:待审核 3: 待激活 4:审核不通过 7:冻结 9:删除
    if (user.status !== '1') {
      if (typeof errorMsg.value !== 'undefined') {
        window.$ui.msg({ type: 'warning', message: '用户名或密码错误，请重新登录' })
      }

      return
    }

    const hasOnlyQrCodeLoginRole = user.roleIdList.filter(roleId => window.$app.onlyQrCodeLoginRoles.includes(roleId)).length > 0

    if (isUsernameLogin.value && grantType.value === 'password' && hasOnlyQrCodeLoginRole) {
      window.$ui.msg({
        type: 'warning',
        message: '教师请用客户端扫码登录'
      })
      return
    }

    // 用户合法的角色列表
    let validRoles = user.roleIdList // window.$app.appRoles.filter((role) => user.roleIdList.includes(role))

    if (validRoles.length > 0) {
      user.token = user.token || accessToken
      // .login.getStudentTokenByParent.data.access_token || .login.getToken.data.access_token

      // 多角色用户，用权限从高到底筛选用户登录后的角色
      if (validRoles.includes(cnt.ROLE_REGION_ADMIN) ||
        validRoles.includes(cnt.ROLE_TENANT_ADMIN)) {
        // 考试管理员登录
        user.isQyAdmin = true
        user.role = cnt.ROLE_REGION_ADMIN
        user.roleName = 'regionAdmin'
      } else if (validRoles.includes(cnt.ROLE_SCHOOL_ADMIN) ||
      validRoles.includes(cnt.ROLE_HEADMASTER) ||
      validRoles.includes(cnt.ROLE_EDU_ADMIN)) {
        user.isAdmin = true
        user.roleName = 'schoolAdmin'
      } else if (validRoles.includes(cnt.ROLE_TEEWON_ADMIN)) {
        // 运营管理员登录
        user.role = cnt.ROLE_TEEWON_ADMIN
        user.roleName = 'teewonAdmin'
      } else if (validRoles.includes(cnt.ROLE_TEACHER)) {
        // 老师登录
        user.role = cnt.ROLE_TEACHER
        user.roleName = 'teacher'
      } else if (validRoles.includes(cnt.ROLE_STUDENT) || validRoles.includes(cnt.ROLE_GUARDIAN)) {
        // 家长与学生登录，都分配为学生角色
        user.role = cnt.ROLE_STUDENT
        user.roleName = 'student'
      }

      window.$ui.setDefaultHeaders({
        'Branch_Code': user.branchCode,
        'Tenant-Id': user.branchCode,
        'Access-Token': user.token,
        'X-User-Account': user.userId,
        'Current-Org-Id': user.orgId,
        'Role-Id': user.role
      })

      // 应用授权给用户
      window.$app.setAuth({
        ...user
      })
      // 开启了双因子认证
      const doubleAuthentic = localStorage.getItem('doubleAuthentic')
      if (doubleAuthentic === '1' && !window.$ui.urlQuery.accredit_code) {
        secondaryValidationVisible.value = true
        return
      }

      // 基础数据接口
      let baseDataApis = []

      if (validRoles.includes(cnt.ROLE_STUDENT) || validRoles.includes(cnt.ROLE_GUARDIAN)) {
        // 学生获取学生档案数据
        baseDataApis.push(await $api.getStudentInfo({id: user.userId}).then(data => {
          window.$app.setAuth({
            classId: data.classId,
            className: data.className,
            studentStatus: data.status,
            studentInfo: data
          }, true)
        }))

        // 获取学生班级数据
        baseDataApis.push(await $api.getClass({
          classId: user.classId,
          classType: cnt.CLASS_TYPE_XZB
        }).then(data => {
          window.$app.setAuth({
            grade: data.grade,
            gradeName: data.gradeName,
            section: data.section,
            sectionName: data.sectionName,
            schoolType: data.schoolType,
            classStatus: data.status,
            classInfo: data
          }, true)
        }))
      }

      if (validRoles.includes(cnt.ROLE_TEACHER)) {
        // 老师获取任教信息
        baseDataApis.push(await $api.queryTeachs({
          userId: user.userId
        }).then(data => {
          window.$app.setAuth({
            teachInfo: data.list
          }, true)
        }))
      }

      baseDataApis.push(await $api.getUserRightList({
        roleId: user.roleId
      }).then(data => {
        window.$app.setAuth({
          authList: data.list
        }, true)
      }))

      // 学段
      if (!user.roleIdList.includes(cnt.ROLE_SUPER_ADMIN)) {
        let configKeys = ['aiclass_show_sharerange']
        baseDataApis.push(await $api.getSystemConfigsByKeys({
          searchKeyList: configKeys,
          status: '1',
          orgId: user.orgId
        }).then(resp => {
          let list = resp.list || []
          let shareRange = '-1'
          if (list.length > 0) {
            shareRange = list[0].value || '-1'
          }

          window.$app.setAuth({
            shareRange: shareRange
          }, true)
        }))
      }

      Promise.all(baseDataApis).then(() => {
        captchaData.base64Img = ''
        captchaData.captchaCode = ''
        // 跳到app-config.js中定义的系统首页

        if (!props.inDialog) {
          let redirect = {
            name: 'forms'
          }
          if (route.query.redirect) {
            redirect = decodeURIComponent(route.query.redirect)
          }
          router.replace(redirect)
        } else {
          emit('close')
        }
      }).catch(e => {
        window.$app.delAuth()
        window.$ui.msg({ type: 'error', message: e.message || '基础数据获取失败' })
      })
    } else {
      if (typeof errorMsg.value !== 'undefined') {
        sending.value = false

        if (window.$app.appType === 'web') {
          if (window.$ui.urlQuery.accredit_code) {
            window.$ui.msg('请用老师、考试管理员、运营管理员登录')
            setTimeout(() => {
              location.href = window.$app.eco.webSever
            }, 3000)
          } else {
            errorMsg.value = '请用老师、考试管理员、运营管理员登录'
          }
        } else {
          window.$ui.msg('请用老师、学生、家长帐号登录')
        }
      }
    }
  }

  // components: {
  //   secondaryValidation
  // }


  const downloadApp = () => {
    let href = window.$app.downloadUrl || './update/AiAppraise_V001R001C09B01.exe'
    downLoadApp(href)
  }
  const confirmSecondaryValidation = (user) => {
    console.log('双因子验证成功')
    doubleAuthentic.value = false
    handleUserInfo(user)
  }

  const LoginThirdPart = (type) => {
    let appId = ''
    let redictUrl = ''
    let state = ''
    let href = ''
    let value = loginThirdParams
    if (value.redirectUrl) {
      redictUrl = value.redirectUrl
    }
    if (value.state) {
      state = value.state
    }
    if (type === '1' || type === '2') {
      if (value.appId) {
        appId = value.appId
      }
    }
    if ((appId && appId === '') || (redictUrl && redictUrl === '')) {
      if (['1', '2', '3'].includes(type) && state && state === '') {
        errorMsg.value = '丢失配置参数'
      }
    }

    redictUrl = encodeURIComponent(
      redictUrl +
      '&bindType=' +
      type +
      '&redirectType=1&ecoappid=' +
      window.$app.appId +
      '&urlBindCode=third_bind_redirect_uri'
    )
    if (type === '1') {
      href =
        'https://open.weixin.qq.com/connect/qrconnect?appid=' +
        appId +
        '&redirect_uri=' +
        redictUrl +
        '&response_type=code&scope=snsapi_login&state=' +
        state
    }
    if (['1', '2', '3'].includes(type)) {
      window.open(href, '_self')
    }
  }

  /**
   * 功能: 自动填充保存的密码
   */
  const writeLocalUser = () => {
    const localUser = window.localStorage.getItem(userLocalKey)

    if (localUser) {
      const user = JSON.parse(window.$ui.toDecrypt(localUser))
      Object.assign(formData, user)
    }
  }

  /**
   * 功能: 打开下载弹窗
   * @param {String} type 二维码类型 ios android
   */
  const openQrModal = (type) => {
    qrCodeModal.visible = true
    qrCodeModal.type = type
  }

  /**
   * 功能: 获取扫码的二维码
   */
  const getTeachQRCode = async () => {
    // type：1-校比邻 2-aiclass
    // 获取二维码时先清除之前定时器调用的接口
    clearLoop()
    const data = await $api.getTeachQRCode({
      type: qrcodeType.value
    })

    invalidCode.value = false
    const { responseEntity, serverResult } = data
    if (serverResult.resultCode === '200') {
      // const prefix = `data:image/png;base64,`
      const prefix = ``
      qrCode.value =
        responseEntity.img.indexOf(`data:image`) !== -1
          ? responseEntity.img
          : `${prefix}${responseEntity.img}`
      screenId.value = responseEntity.screenId

      invalidCodeTime.value = setTimeout(() => {
        console.log('二维码失效了')
        invalidCode.value = true
        clearLoop()
      }, 180000)
      loopScreenSuccess()
    } else {
      window.$ui.msg({
        type: 'warning',
        message: serverResult.resultMessage
      })
    }

    console.log('二维码', qrCode.value)
  }

  /**
   * 功能: 轮询处理扫码是否成功
   */
  const loopScreenSuccess = async () => {
    try {
      // 轮询处理扫码是否成功
      const data = await $api.screenSuccess({
        screenId: screenId.value,
        type: qrcodeType.value
      })

      const { responseEntity, serverResult } = data

      if (serverResult.resultCode === '200') {
        clearLoop()
        window.$ui.msg({ type: 'success', message: '扫码成功，正在跳转...' })
        loginForQrCode(responseEntity.padData) // 老版本用的PadData
        setTimeout(() => {
          // 刷新下二维码以防家长扫码后停留在当前页面
          getTeachQRCode()
        }, 1000)
      } else if (serverResult.resultCode === '99999') {
        clearLoop()
        invalidCode.value = true
      } else {
        loopTimer.value = setTimeout(() => {
          loopScreenSuccess()
        }, 3000)
        // }
      }
    } catch(e) {
      setTimeout(() => {
        // 刷新下二维码以防家长扫码后停留在当前页面
        getTeachQRCode()
      }, 1000)
    }
  }

  /**
   * 功能: 清空轮询
   */
  const clearLoop = () => {
    times.value = 0
    clearTimeout(loopTimer.value)
    clearTimeout(invalidCodeTime.value)
    // bgtimers.value && clearTimeout(bgtimers.value)
  }

  /**
   * 功能: 登录
   */
  const handleLogin = async () => {
    window.$app.delAuth()
    if (formData.username === '') {
      window.$ui.msg({ type: 'warning', message: '请输入用户名' })
      return
    }

    if (formData.password === '') {
      window.$ui.msg({ type: 'warning', message: '请输入密码' })
      return
    }

    if (userOrgList.length > 1 && formData.uid === '') {
      window.$ui.msg({ type: 'warning', message: '请选择机构及角色' })
      return
    }

    if (verifyCodeType.value === 'eco') {
      if (
        captchaData.base64Img &&
        !formData.captchaText
      ) {
        window.$ui.msg({ type: 'warning', message: '请输入验证码' })
        return
      } else {
        formData.captchaCode =
        captchaData.captchaCode
      }
    } else {
      if (verifyCode.value) {
        if (formData.captchaText) {
          if (!verifyCode.value.validate(formData.captchaText)) {
            window.$ui.msg({ type: 'warning', message: '验证码错误' })
            formData.captchaText = ''
            return
          }
        } else {
          window.$ui.msg({ type: 'warning', message: '请输入验证码' })
          return
        }
      }
    }

    if (sending.value) {
      return
    } else {
      sending.value = true
    }

    formData.client_type = 1
    formData.grant_type = grantType.value
    await $api.getToken({
      ...formData
    })
    .then((data) => {
      if (data.errorCode === 8008 || data.errorCode === 8026) {
        errorMsg.value = data.errorMesage
        sending.value = false

        window.$ui.msg({ type: 'error', message: data.errorMesage })

        captchaVisibale.value = true

        if (verifyCodeType.value === 'eco') {
          $api.captchaView()
        } else {
          // genrateVerifyCode()
        }

        return
      }

      accessToken.value = data.access_token
      let user = data.user || {}
      user.token = data.access_token
      store.dispatch('ecouser/login', {
        username: user.realName || '',
        token: data.access_token
      })
      store.commit('ecouser/setUser', user)

      if (grantType.value === 'password' && data.s2FAS === 1 && data.c2FARA === 1) {
        localStorage.setItem('doubleAuthentic', '1')
        doubleAuthentic.value = true
        localStorage.setItem('doubleAuthenticParamas', JSON.stringify(formData))
      }

      if (
        window.$ui.urlQuery.parent_accredit_code &&
        !window.$ui.isEmptyValue(window.$ui.urlQuery.parent_accredit_code)
      ) {
        let params = {
          studentId: window.$ui.urlQuery.stuId,
          deviceType: window.$ui.urlQuery.deviceType,
          clientType: window.$ui.urlQuery.clientType,
        }

        window.$ui.setDefaultHeaders({
          'Access-Token': data.access_token
        })
        $api.getStudentTokenByParent(params).then(stuSso => {
          accessToken.value = stuSso.access_token
          user.token = stuSso.access_token
          store.commit('ecouser/setUser', user)
          $api.getUser({
            accessToken: accessToken.value
          }).then(response => {
            if (response) {
              console.log(response, 'tokenData')
              Object.assign(user, response.responseEntity)
              handleUserInfo(user)
            }
          }).catch((e) => {
            sending.value = false
          })
        })
      } else {
        $api.getUser({
          accessToken: accessToken.value
        }).then(response => {
          if (response) {
            console.log(response, 'tokenData')
            Object.assign(user, response.responseEntity)
            handleUserInfo(user)
          }
        }).catch((e) => {
          sending.value = false
        })
      }
    })
    .catch((e) => {
      console.log(e)
      sending.value = false
      window.$ui.msg({ type: 'error', message: e.errorMesage || '' })
    })
  }
   /**
   * 功能: 生成前端本地验证码
   */
  // const genrateVerifyCode = () => {
  //   nextTick(() => {
  //     verifyCode.value = new GVerify('vcode')
  //   })
  // }
  /**
   * 功能: 扫码登录
   */
  const loginForQrCode = (padData) => {
    const user = {
      padUrl: padData.url || '',
      token: padData.userToken,
      ...padData.userInfo
    }
    handleUserInfo(user)
  }

  const retCurrentFlavor = (data) => {
    console.log(data, 'retCurrentFlavor')
    window.$app.flaver = data
    window.localStorage.setItem('flaver', window.$app.flaver)
    console.log(window.$app, '$app....')
  }

  const logoinfo = (options = {}) => {
    return new Promise((resolve, reject) => {
      let params = {
        ifFooter: '0',
        checkRepeat: options.checkRepeat || '0' // 查重--默认0不查重1查重
      }
      if (options.domain) {
        params.domain = options.domain
      }
      if (options.appId) {
        params.appId = options.appId
      }
      if (options.tenantId) {
        params.tenantId = options.tenantId
      }
      if (options.roleId) {
        params.roleId = options.roleId
      }
      $api.getLogoInfo(params)
        .then((response) => {
          resolve(response)
        }).catch(()=>{})
    })
  }
  const getAppLogo = async () => {
    let tenantId = window.$app.user && window.$app.user.branchCode ? window.$app.user.branchCode : ''

    let param = {}
    if (tenantId) {
      param = {
        appId: window.$app.appId,
        tenantId: tenantId,
        roleId: window.$app.user.roleId,
        checkRepeat: '1'
      }
    } else {
      let path = window.location.host + (window.location.pathname.indexOf('.') ? window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1) : window.location.pathname)
      param = {
        domain: path, // 'http://192.168.128.119/ecrweb/home', // 'http://www.baidu.com',
        checkRepeat: '1'
      }
    }
    await logoinfo(param).then((res) => {
      if (res && res.data && res.data.responseEntity) {
        Object.assign(logoInfo, res.data.responseEntity)
        if (logoInfo.setting) {
          logoInfo.othersetting = JSON.parse(logoInfo.setting)
        }

        if (logoInfo.logoUrl) {
          logoInfo.logoUrl =
          window.$app.fileBaseUrl + logoInfo.logoUrl
        }
        if (logoInfo.iconUrl) {
          logoInfo.iconUrl =
          window.$app.fileBaseUrl + logoInfo.iconUrl
        }
        if (logoInfo.businessLicense) {
          logoInfo.businessLicense =
          window.$app.fileBaseUrl +
            logoInfo.businessLicense
        }
      } else {
       Object.assign(logoInfo, {
          logoid: '',
          appid: '',
          logotype: '',
          logoUrl: '',
          title: '',
          copyright: '',
          versionNumber: '',
          businessLicense: '',
          recordNumber: '',
          recordConnection: '',
          iconUrl: '',
          domainUrl: '',
          platformTitle: '',
          loginTitle: '',
          createTime: '',
          lastmodifytime: '',
          status: ''
        })
      }
      
      updateLogo()
    }).catch(() => {})
  }

  const updateLogo = () => {
    if (logoInfo.title) {
      document.title = logoInfo.title || '自定义表单'
    } else if (logoInfo.logoid) {
      // document.title = logoInfo.title || '自定义表单'
    }

    if (logoInfo.iconUrl) {
      let doms = document.querySelectorAll('link')
      let t = 0
      for(let i = 0; i < doms.length; i++) {
        if (doms[i].rel === 'icon') {
          doms[i].href = logoInfo.iconUrl
          doms[i].type = 'image/png'
          
          t += 1
        }
      }
    
      if (t === 0) {
        var link = document.createElement('link')
        link.href = logoInfo.iconUrl
        link.rel = 'icon'
        link.type = 'image/png'
        document.querySelector('head').appendChild(link)
      }
    } else if (logoInfo.logoid) {
      let doms = document.querySelectorAll('link')
      for (let i = 0; i < doms.length; i++) {
        if (doms[i].rel === 'icon') {
          doms[i].href = 'data:;'
        }
      }
    }
    store.commit('ecouser/setLogoInfo', logoInfo)
  }
  
  const changeLoginType = () => {
    isUsernameLogin.value = !isUsernameLogin.value;
    if (isUsernameLogin.value) {
      clearLoop();
    } else {
      getTeachQRCode()
    }
  }

  onMounted(() => {
    captchaData.base64Img = ''
    captchaData.captchaCode = ''
    // 用信任码登录，不走界面逻辑，直接获取token
    if (window.$ui.urlQuery.accredit_code) {
      if (window.$app.appType === 'pad') {
        window.retCurrentFlavor = retCurrentFlavor
        window.$ui.getCurrentFlavor()
      }
      window.$app.delAuth()
      grantType.value = 'client_credentials'
      $api.getToken({
        client_type: 2,
        grant_type: grantType.value,
        accredit_code: window.$ui.urlQuery.accredit_code
      }).then((data) => {
        if (data.errorCode === 8008 || data.errorCode === 8026) {
          errorMsg.value = data.errorMesage
          sending.value = false

          window.$ui.msg({ type: 'error', message: data.errorMesage })
          return
        }

        accessToken.value = data.access_token
        let user = data?.user || {}
        user.token = data.access_token
        store.dispatch('ecouser/login', {
          username: user?.realName || '',
          token: data.access_token
        })
        store.commit('ecouser/setUser', user)

        if (
          window.$ui.urlQuery.parent_accredit_code &&
          !window.$ui.isEmptyValue(window.$ui.urlQuery.parent_accredit_code)
        ) {
          let params = {
            studentId: window.$ui.urlQuery.stuId,
            deviceType: window.$ui.urlQuery.deviceType,
            clientType: window.$ui.urlQuery.clientType,
          }

          window.$ui.setDefaultHeaders({
            'Access-Token': data.access_token
          })
          $api.getStudentTokenByParent(params).then(stuSso => {
            accessToken.value = stuSso.access_token
            user.token = stuSso.access_token
            store.commit('ecouser/setUser', user)
            $api.getUser({
              accessToken: accessToken.value
            }).then(response => {
              if (response) {
                console.log(response, 'tokenData')
                Object.assign(user, response.responseEntity)
                handleUserInfo(user)
              }
            }).catch((e) => {
              console.log(e)
              sending.value = false
            })
          })
        } else {
          $api.getUser({
            accessToken: accessToken.value
          }).then(response => {
            if (response) {
              console.log(response, 'tokenData')
              Object.assign(user, response.responseEntity)
              handleUserInfo(user)
            }
          }).catch((e) => {
            console.log(e)
            sending.value = false
          })
        }
      })
      .catch((e) => {
        console.log(e)
        sending.value = false
        window.$ui.msg({ type: 'error', message: e.errorMesage || '' })
      })
    } else if (window.$app.appType === 'pc') {
      loginVisible.value = false
      grantType.value = 'client_credentials'
    } else {
      // 系统已授权时，访问登录页直接跳到首页
      if (window.$app?.user?.token) {
        if (!props.inDialog) {
          router.push({name: 'forms'})
        } else {
          emit('close')
        }
      } else {
        writeLocalUser()
        loginVisible.value = true
        grantType.value = 'password'

        if (!props.inDialog) {
          getAppLogo().then(() => {
            nextTick(() => {
              logoloading.value = true
            })
          }).catch(() => {
            nextTick(() => {
              logoloading.value = true
            })
          })
        }
      }
    }

    if (!props.inDialog) {
      // bgtimers.value = setInterval(() => {
      //   bgtimer.value = !bgtimer.value
      // }, 3000)
    }
 
    if (window.$app.defaultLoginType === 'qrcode') {
      // 默认登录如果是二维码登录，默认显示二维码
      isUsernameLogin.value = false
      getTeachQRCode()
    }
  })

  onUnmounted(() => {
    clearLoop()
  })

</script>

<style lang="scss" scoped>
#app {
  background: url("./images/login-bg.svg") no-repeat;
  background-size: 100%;
  object-fit: fill;
}
</style>
<style lang="scss" >
@use "./login.scss";
</style>
